import Taro from '@tarojs/taro'
import { baseUrl } from '../config'

export function request (method, url, data, options = {}) {
  const { auth = true, headers, showToast = true } = options
  let header = headers ? headers : {
    'content-type': 'application/json',
  };
  // alert(Taro.getStorageSync('token'))
  return Taro.request({
    url: `${baseUrl}${url}`,
    method,
    data,
    dataType: 'json',
    header
  }).then((res) => {
    if (res.header && res.header['RefreshToken']) {
      //更新快过期的token
      Taro.setStorageSync('token', res.header['RefreshToken'])
    }
    const data = res.data;
    if (data.flag) {
      /*showToast && Taro.showToast({
        title: `${data.error}`,
        icon: 'none',
        duration: 1000
      });*/
      return data
    } else {
      showToast && Taro.showToast({
        title: `[${data.status}] ${data.error}`,
        icon: 'none',
        duration: 2000
      });
      throw data
    }
  })
}
